package client

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"
)

func WatchHealthServer(ipAddr string, shutdownFunc func()) {
	Conn, err := grpc.Dial(ipAddr,
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(
			fmt.Sprintf(`{"HealthCheckConfig": {"ServiceName": "%s"}}`, "grpc.health.v1.Health")))
	if err != nil {
		panic(err)
	}
	client := healthpb.NewHealthClient(Conn)
	wc, err := client.Watch(context.Background(), &healthpb.HealthCheckRequest{
		Service: "grpc.health.v1.Health",
	})
	if err != nil {
		panic(err)
	}
	go func(fc func()) {
		for {
			data, err := wc.Recv()
			if err != nil {
				fmt.Println(fmt.Sprintf("监听%s服务异常：%s", ipAddr, err.Error()))
				fc()
				return
			}
			if data.Status != healthpb.HealthCheckResponse_SERVING {
				fmt.Println("服务健康状态不正常！当前服务健康状态为" +
					healthpb.HealthCheckResponse_ServingStatus_name[int32(data.Status)])
				fc()
				return
			}
			fmt.Println(fmt.Sprintf("ip=%s当前状态正常", ipAddr))
		}
	}(shutdownFunc)
}
